import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';
import { NotificationService } from "../../shared/utils/notification.service";

declare var $: any;
declare var BMap: any;
declare var toMapPointArr: any;
declare var toWGS84: any;
@Component({
	selector: 'sa-path-fix',
	templateUrl: './path-fix.component.html',
	styleUrls:['./path-fix.css']
})
export class PathFixComponent implements OnInit {
	myMap:any='';
	mapSize:any='';
    roadListArr=[];//所有轨迹数据
    deviceId='';
    carNumber='';
    lookLine:any;
    startMarker:any;
    endMarker:any; //点击查看轨迹时的轨迹路线,起点，终点
    selectItemId:any;//复选框选中路线的id;
    roadLength=0;//路线轨迹总条数
    totalDistance=0;//路线轨迹总路程
   
   	polylineObj = []; //对应的ltem的轨迹
	labelObj = []; //对应的ltem的轨迹的终点label
	
   	isUplodTrack=false;//监听上传轨迹模块是否打开
   	fileToUpload: File = null;//上传路线轨迹的文件
   	roadName='';//上传的路线名
   	remark='';//上传的描述
   	
   	isloading=true;//判断数据是否除以加载中
	isRemove=false;
   	
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService, private notificationService: NotificationService){} 

 	//初始化轨迹list
	initListData(){
		this.isloading=true;
		this.jsonApiService.http("track/getallroad.html", '').subscribe(result => {
			this.isloading=false;
			this.roadListArr=result.data;
			let len=result.data.length;
			let allDistance=0;
			for(let i=0;i<len;i++){
				let distance=parseInt(result.data[i].distance)/1000;
				allDistance=allDistance+distance;
				result.data[i].distance=Math.floor(distance*100)/100;//距离m转换km,保留小数后2位
				this.polylineObj[i] = '0';
				this.labelObj[i]='0';
			}
			this.roadLength=len;
			this.totalDistance=Math.floor(allDistance*100)/100;
		})
	}
	//checkInput 选中一条轨迹路线
	selectItem(e,id){
		e.stopPropagation();
		this.selectItemId=id;
	}
	//点击查看轨迹
	lookTrack(){
		if(this.lookLine) {
			this.myMap.removeOverlay(this.lookLine);
			this.myMap.removeOverlay(this.startMarker);
			this.myMap.removeOverlay(this.endMarker);
		}
		let deviceId = this.deviceId;
		this.myMap.closeInfoWindow(); 
		let startTime = $("#datetimepicker1").val();
		let endTime = $("#datetimepicker2").val();
//		let deviceId = '431453255';
//		let startTime = '2018-05-10 00:00:14';
//		let endTime = '2018-05-10 23:00:14';
		if(deviceId==''){
			this.message('设备ID不能为空');
			return;
		}
		layer.load();
		let reqdata='deviceId='+deviceId+'&startTime='+startTime+'&endTime='+endTime;
		this.jsonApiService.http('track/localtrack.html',reqdata).subscribe(result=>{
			layer.closeAll('loading');
			if(result.data.length<2){
				this.message('该时间段没有数据');
				return;
			}
			let paramArr = toMapPointArr(result.data);
			this.drawTrackLine(paramArr,false);
			this.myMap.centerAndZoom(new BMap.Point(paramArr[0].lng, paramArr[0].lat), 12);
		})
	}
	//画查看轨迹的路线
	drawTrackLine(paramArr,paramColor) {
		let lineArr = [];
		for(let i = 0; i < paramArr.length; i++) {
			let p = new BMap.Point(paramArr[i].lng, paramArr[i].lat);
			lineArr.push(p)
		}
		let color = "blue";
		if(paramColor) {
			color = paramColor;
		}
		let polyline = new BMap.Polyline(lineArr, {
			strokeColor: color,
			strokeWeight: 6,
			strokeOpacity: 0.5
		}); //创建路线
		this.lookLine = polyline;
		let myIcon1 = new BMap.Icon("assets/img/trackImage/startMarker.png", new BMap.Size(20, 50));
		let myIcon2 = new BMap.Icon("assets/img/trackImage/endMarker.png", new BMap.Size(20, 50));
		this.startMarker = new BMap.Marker(paramArr[0],{icon: myIcon1});  // 起点
		this.endMarker = new BMap.Marker(paramArr[paramArr.length-1],{icon: myIcon2});  // 终点
		this.myMap.addOverlay(this.startMarker);              
		this.myMap.addOverlay(this.endMarker);
		this.myMap.addOverlay(this.lookLine);
		let options = {
    		size: 7,
            shape: 3,
            color: 'rgba(0, 0, 0, 0)'
    	};
		let pointCollection = new BMap.PointCollection(paramArr, options); // 初始化PointCollection
		let that=this;
		pointCollection.addEventListener('click', function (e) {
//	    	that.createTextInfo(e);
			var geturl=config.BaseURL;
			e.point.deviceId=that.deviceId;
			common.createInfoBox(that.myMap,e.point,geturl);
	  });
		this.myMap.addOverlay(pointCollection); 
	}
	//创建textInfo信息窗口
	createTextInfo(obj){
		let content = '<div class="">'+
		'<ul>'+
		'<li><span class="leftSpan">载重量：</span><span class="rightSpan">'+ obj.point.weight +'（吨）</span></li>'+	
		'<li><span class="leftSpan">速度：</span><span class="rightSpan">'+ obj.point.speed +' KM/H</span></li>'+	
		'<li><span class="leftSpan">经度：</span><span class="rightSpan">'+ obj.point.lng +'</span></li>'+
		'<li><span class="leftSpan">纬度：</span><span class="rightSpan">'+ obj.point.lat +'</span></li>'+
		'<li><span class="leftSpan">时间：</span><span class="rightSpan">'+timestampToTime(obj.point.loc_time)+'</span></li>'+
		'</ul>'+
		'</div>';
		let opts = {width: 270, heigth: 240};
		let infoWindow =  new BMap.InfoWindow(content, opts);
		this.myMap.openInfoWindow(infoWindow,new BMap.Point(obj.point.lng, obj.point.lat)); //开启信息窗口
	}
	//单一条轨迹路线的点击事件
	listItemEvent(){
		let that=this;
		$('.trackList ').delegate('.liItem','click',function(e) {
			let isSelect = $(this).attr('class').split(' ')[1];
			let sortItem = parseInt($(this).find('.sortTrack').text());
			if(!isSelect) {
				$(this).addClass('selectItem');
				that.drawItemLine(sortItem);
			} else {
				$(this).removeClass('selectItem');
				that.myMap.removeOverlay(that.polylineObj[sortItem - 1]);
				that.myMap.removeOverlay(that.labelObj[sortItem - 1]);
				that.polylineObj[sortItem - 1] = '0';
				that.labelObj[sortItem - 1] = '0';
			}
		})
	}
	//绘画选定轨迹item路线
	drawItemLine(sortItem) {
		let trackId=this.roadListArr[sortItem - 1].id;
		if(!trackId){
			this.jsonApiService.message('未获取到轨迹id');
			return;
		}
		let reqdata='trackId='+trackId;
		this.jsonApiService.http("track/getroad.html", reqdata).subscribe(result => {
			let darw=toMapPointArr(result.data.pointList);//转成百度坐标系
			if(darw.length<2){
				this.message('该路线没有数据');
				return;
			}
			let lineArr = [];
			for(var i = 0; i < darw.length; i++) {
				var p = new BMap.Point(darw[i].lng, darw[i].lat);
				lineArr.push(p)
			}
			let color = "blue";
			if(sortItem % 4 == 3) {
				color = "black"
			}
			if(sortItem % 4 == 2) {
				color = "red"
			}
			if(sortItem % 4 == 1) {
				color = "#d15b47"
			}
			if(sortItem % 4 == 0) {
				color = "blue"
			}
			let polyline = new BMap.Polyline(lineArr, {
				strokeColor: color,
				strokeWeight: 6,
				strokeOpacity: 0.6
			}); //创建路线
			
			this.polylineObj[sortItem - 1] = polyline
			this.myMap.addOverlay(this.polylineObj[sortItem - 1]);
			let point = new BMap.Point(darw[darw.length-1].lng,darw[darw.length-1].lat);
			let opts = {
		  		position : point,    // 文本标注位置
		  		offset   : new BMap.Size(0, 0)    //文本偏移量
			}
			let label = new BMap.Label("终点", opts);  // 创建文本标注对象
				label.setStyle({
					 color : color,
					 fontSize : "12px",
					 height : "20px",
					 lineHeight : "20px",
					 fontFamily:"微软雅黑",
					 'padding-right': '27px',
					 border:'none'
				 });
			this.myMap.addOverlay(label);   
			this.labelObj[sortItem - 1] = label;
		})
	}
	//地图点击获取起始点坐标位置
	getPointEvent() {
		var getPointStatus;
		$('.focusInp').focus(function() {
			$('.getMapPoint').removeClass('getMapPoint');
			$(this).addClass('getMapPoint');
			getPointStatus = true;
		})
		$('.focusInp').blur(function() {
			$(this).removeClass('getMapPoint');
			getPointStatus = false;
		})
		function getPoint(e) {
			if(!getPointStatus) {
				return;
			}
			var wgsPoint=toWGS84(e.point);
			if(wgsPoint){
				$('.getMapPoint').val(wgsPoint.lng + "," + wgsPoint.lat);
			}
		}
		this.myMap.addEventListener("click", getPoint);
	}
	//点击修复轨迹获取所选参数
	getRodioTrack() {
		if(!this.selectItemId){
			this.message('请选择需要修复的轨迹');
			return;
		}
		let isSubmit = true;
		let postData:any = {
			roadId:this.selectItemId
		};
		$.each($('#formContent').serializeArray(), function() {
			if(this.value == '') {
				isSubmit = false;
			}
			postData[this.name] = this.value;
		});
		if(postData.isCover == 'on') {
			postData.isCover = true; //是否选择覆盖轨迹
		} else {
			postData.isCover = false;
		}
		if(postData.isRemove == 'on') {
			postData.isRemove = true; //是否选择覆盖轨迹
		} else {
			postData.isRemove = false;
		}
		if(postData.isMakeup == 'on') {
			postData.isMakeup = true; //是否选择覆盖轨迹
		} else {
			postData.isMakeup = false;
		}
		if(postData.starPoint !== '') {
			postData.startLng = postData.starPoint.split(',')[0];
			postData.startLat = postData.starPoint.split(',')[1];
			if(!postData.startLng || !postData.startLat) {
				this.message('请检查坐标格式是否正确');
				return;
			}
		}
		if(postData.endPoint !== '') {
			postData.endLng = postData.endPoint.split(',')[0];
			postData.endLat = postData.endPoint.split(',')[1];
			if(!postData.endLng || !postData.endLat) {
				this.message('请检查坐标格式是否正确');
				return;
			}
		}
		if(!isSubmit) {
			this.message('请检查信息是否填写完整');
				return;
		}
		let that=this;
		let isTimeType=true;
		$('.timeType').each(function(){
			let type=that.checkDateTime($(this).val());
			if(!type){
				isTimeType=false;
			}
		})
		if(!isTimeType){
			that.message('请检查输入的时间格式是否正确');
			return;
		}
		layer.load();
		$.ajax({
			type: 'POST',
			url : config.BaseURL+"track/autoretifytrack.html",
	        xhrFields: {
				withCredentials: true
			},
			data: postData,
			dataType: "json",
			success: function(result) {
				layer.closeAll('loading');
				that.message(result.message);
			},
			error: function() {
				that.message('网络错误，请联系管理员');
			}
		})
	}
	/**点击撤销轨迹获取所选参数*/
	revokeTrack() {
		if(this.deviceId == '') {
			this.message('请输入设备编号');
			return;
		}
		let startTime = $("#datetimepicker1").val();
		let endTime = $("#datetimepicker2").val();
		let reqdata='deviceId='+this.deviceId+'&startTime='+startTime+'&endTime='+endTime+'&isRemove='+this.isRemove;
		this.jsonApiService.http("track/canceltrack.html", reqdata).subscribe(result => {
			this.message(result.message);
		})
	}
	//打开或关闭上传轨迹模块
	isOpenUplod(status){
		if(status=='open'){
			this.isUplodTrack=true;
		}
		else{
			this.isUplodTrack=false;
			
		}
	}
	//获取需要上传的文件
	getFile(files: FileList) {
		this.fileToUpload = files.item(0);
		if(!this.fileToUpload){
			this.message('请选择文件')
			return false;
		}
   }
	//提交上传的轨迹
	submitUpload(){
		if(this.roadName==''){
			this.message('请输入上传的轨迹名称');
        	return false;
		}
		if(this.remark==''){
			this.message('请输入上传的轨迹描述');
        	return false;
		}
		if(!this.fileToUpload){
     		this.message('请选择需要上传的文件');
        	return false;
       }
		let reqdata = new FormData();
        reqdata.append('roadName', this.roadName);
        reqdata.append('remark', this.remark);
        reqdata.append('file', this.fileToUpload);
		this.jsonApiService.form_http("track/uploadroadfile.html", reqdata).subscribe(result => {
			this.message(result.message);
			if(!result.success){
				return;
			}
			this.isUplodTrack=false;
			this.roadName='';
			this.remark='';
			let len=this.polylineObj.length;
			for(let i=0;i<len;i++){
				this.myMap.removeOverlay(this.polylineObj[i]);
				this.myMap.removeOverlay(this.labelObj[i]);
			}
			this.initListData();
		})
	}
	//删除路线轨迹
	delTrack(){
		if(!this.selectItemId){
			this.message('请选择需要删除的轨迹路线');
			return;
		}
		this.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			let reqdata='id='+this.selectItemId;
			this.jsonApiService.http('track/deleteroad.html',reqdata).subscribe(result=>{
				this.message(result.message);
				let len=this.roadListArr.length
				for (let i=0;i<len;i++){
					let id=this.roadListArr[i].id;
					if(id==this.selectItemId){
						
						if(this.polylineObj[i]!=='0'){
							this.myMap.removeOverlay(this.polylineObj[i]);
							this.myMap.removeOverlay(this.labelObj[i]);
						}
						this.roadListArr.splice(i,1);
						this.polylineObj.splice(i,1);
						this.labelObj.splice(i,1);
						break;
					}
				}
			})
		})
	}
	//初始化车牌号select2
	intiSelect2(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
			let that=this;
			$("#carNumberSelect2").select2({
		    	language : "zh-CN",
		    	placeholder :"请选择...",
		    	allowClear : true,
		    	minimumInputLength : 2,      //最少2个字符，select2才显示查询的内容
		         
		    	ajax: {
		    		url: config.BaseURL+"stats/carListByCarNumber.html",
		    		dataType: 'json',
		    		delay: 50,
		    		method: "POST",
		    		xhrFields: {
			           withCredentials: true
			      	},
		    		data: function (params) {
		    		    return {
		    		   	 "carNumber" :  params.term // search term
		    		    };
		    		},
		    		processResults: function(data, params) {
						var options = new Array();
						// 小于10个数量才判断重复
						if(data.data.length<=10){
							let arr = []
							let sameCar = []
							// 判断相同的车牌号
							for (let index = 0; index < data.data.length; index++) {
								let car = data.data[index];
								if(arr.indexOf(car.carNumber)!=-1){
									sameCar.push(car.carNumber)
								}else{
									arr.push(car.carNumber);
								}
							}
							$(data.data).each(function(index, car) {
								if(sameCar.indexOf(car.carNumber)!=-1){
									options.push({
										id: car.deviceId,
										text: car.carNumber+"["+car.parentName+"]"
									})
								}else{
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								}
							});
						}else{
							$(data.data).each(function(index, car) {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							});
						}
						return {
							results: options //获取查询后的结果
						};
					},
		    		cache: true
		         },
		         templateResult: this.formatRepo
		    }).on ("select2:select", function (e) {
	        	  var data = e.params.data;
	        	  that.deviceId = data.id;
	        	  if(data.text.indexOf('[') > 0){
					that.carNumber = data.text.split('[')[0];
				  } else {
					that.carNumber = data.text;
				  }
	       });
			 });
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
  	isTimeFormat(value){
  		let isTime=this.checkDateTime(value);
  		if(!isTime){
  			this.message('输入的时间格式不正确,例:2018-08-01 00:00:00');
  		}
  	}
  	检查时间格式
	checkDateTime(str) {
		let reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
		let r = str.match(reg);
		if(r == null) return false;
		r[2] = r[2] - 1;
		let d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]);
		if(d.getFullYear() != r[1]) return false;
		if(d.getMonth() != r[2]) return false;
		if(d.getDate() != r[3]) return false;
		if(d.getHours() != r[4]) return false;
		if(d.getMinutes() != r[5]) return false;
		if(d.getSeconds() != r[6]) return false;
		return true;
	}
  	//提示框
  	message(data){
		this.notificationService.smallBox({
	      content: data,
	      timeout: 1000
	    });
	}
	//带确认提示框
  	confirm_message(message){
		 return new Promise(function (resolve, reject) {
 		    this.notificationService.smartMessageBox({
			      title: "提示",
			      content: message,
			      buttons: '[确认][取消]'
			    }, (ButtonPressed) => {
			    	if(ButtonPressed === "确认"){
			    		resolve();
			    	}
				    if (ButtonPressed === "取消") {
				        this.notificationService.smallBox({
				          content: "操作取消",
				          timeout: 3000
				        });
				        return ;
				    }
			
		    });
		 }.bind(this))
	}
  	ngOnInit() {
  		this.initListData();
		let  that=this;
		that.myMap=new BMap.Map("baiduMap",{enableMapClick: false});//我的地图
		that.myMap.centerAndZoom(new BMap.Point(113.46, 22.27), 10);  // 初始化地图,设置中心点坐标和地图级别
		that.myMap.addEventListener("zoomend", function(){   
			that.mapSize=this.getZoom();
		});
		that.myMap.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
		//导入时间插件插件js
		System.import('assets/js/timeControl.js');
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
					STATS.initTimeWidget();//初始化时间插件 
					STATS.iniParameter();//初始化时间参数
					
				});
			}
		);
		this.intiSelect2();
		this.listItemEvent();
		this.getPointEvent();
  	}
}